<template>
    <div class="app-container">
        <!-- 筛选区域 -->
        <el-card class="search-card">
            <el-form :model="filterForm" class="filter-form">
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-form-item label="站点类型">
                            <el-select v-model="filterForm.siteTypeId" placeholder="请选择站点类型" clearable
                                style="width: 100%" @change="handleFilterChange">
                                <el-option v-for="item in siteTypeOptions" :key="item.dictValue" :label="item.dictLabel"
                                    :value="item.dictValue" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="监测量">
                            <el-select v-model="filterForm.itemId" placeholder="请选择监测量" clearable style="width: 100%"
                                @change="handleFilterChange">
                                <el-option v-for="item in monitoringOptions" :key="item.monitorId"
                                    :label="item.monitorName" :value="item.monitorId" />
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="6">
                        <el-form-item label="站点状态">
                            <el-select v-model="filterForm.status" placeholder="请选择状态" clearable style="width: 100%"
                                @change="handleFilterChange">
                                <el-option label="正常" value="normal" />
                                <el-option label="报警" value="alarm" />
                                <el-option label="离线" value="offline" />
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="6">
                        <div>
                            <el-button type="primary" @click="refreshData" :loading="loading">
                                <el-icon class="el-icon--left">
                                    <Refresh />
                                </el-icon>
                                刷新
                            </el-button>
                            <el-button @click="resetFilter">
                                <el-icon class="el-icon--left">
                                    <Delete />
                                </el-icon>
                                重置
                            </el-button>
                        </div>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>

        <!-- 站点卡片区域 -->
        <div class="cards-container mt-2">
            <div class="cards-grid">
                <el-card v-for="site in siteData" :key="site.siteId" class="site-card" :class="getSiteCardClass(site)">
                    <!-- 卡片头部 -->
                    <div class="card-header">
                        <div class="site-info">
                            <h3 class="site-name">{{ site.siteName }}</h3>
                            <div class="site-type">
                                <el-tag :type="getSiteTypeTag(site.siteTypeId)" size="small">
                                    {{ getSiteTypeName(site.siteTypeId) }}
                                </el-tag>
                            </div>
                        </div>
                        <div class="card-actions">
                            <el-button type="primary" link size="small" @click="handleViewDetail(site)">
                                <el-icon>
                                    <View />
                                </el-icon>
                                详情
                            </el-button>
                            <el-button type="info" link size="small" @click="handleRefreshSite(site)">
                                <el-icon>
                                    <Refresh />
                                </el-icon>
                                刷新
                            </el-button>
                        </div>
                    </div>

                    <!-- 监测数据 -->
                    <div class="monitoring-data">
                        <div v-for="node in site.nodeList" :key="node.nodeName" class="data-item"
                            :class="getDataItemClass(node)">
                            <div class="data-label">
                                <span class="label-text">{{ node.nodeName }}</span>
                                <el-tooltip v-if="getMonitoringUnit(node.nodeName)"
                                    :content="getMonitoringUnit(node.nodeName)" placement="top">
                                    <el-icon class="unit-icon">
                                        <InfoFilled />
                                    </el-icon>
                                </el-tooltip>
                            </div>
                            <div class="data-value">
                                <span class="value-number">{{ node.val || '-' }}</span>
                                <span class="value-unit" v-if="getMonitoringUnit(node.nodeName)">
                                    {{ getMonitoringUnit(node.nodeName) }}
                                </span>
                            </div>
                            <div class="data-status">
                                <el-tag :type="getStatusTag(node.status)" size="small" effect="light">
                                    {{ getStatusText(node.status) }}
                                </el-tag>
                            </div>
                            <div class="data-time">
                                {{ formatTime(node.collectTime) }}
                            </div>
                        </div>
                    </div>
                </el-card>
            </div>
        </div>

        <!-- 站点详情对话框 -->
        <el-dialog v-model="detailDialogVisible" :title="detailTitle" width="900px"
            :before-close="handleCloseDetailDialog">
            <div v-if="currentSiteDetail" class="site-detail">
                <!-- 基本信息 -->
                <el-descriptions title="基本信息" :column="2" border>
                    <el-descriptions-item label="站点ID">{{ currentSiteDetail.siteId || '-' }}</el-descriptions-item>
                    <el-descriptions-item label="站点名称">{{ currentSiteDetail.siteName || '-' }}</el-descriptions-item>
                    <el-descriptions-item label="站点类型">
                        <el-tag :type="getSiteTypeTag(currentSiteDetail.siteType)" size="small">
                            {{ getName(siteTypeOptions,currentSiteDetail.siteType ,'dictValue','dictLabel') }}
                        </el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="负责人">{{ currentSiteDetail.principal || '-' }}</el-descriptions-item>
                    <el-descriptions-item label="联系人">{{ currentSiteDetail.contact || '-' }}</el-descriptions-item>
                    <el-descriptions-item label="站点地址">{{ currentSiteDetail.siteAddress || '-' }}</el-descriptions-item>
                    <el-descriptions-item label="地理位置">{{ currentSiteDetail.location || '-' }}</el-descriptions-item>
                    <el-descriptions-item label="运行状态">
                        <el-tag :type="getStatusTag(currentSiteDetail.status)" size="small">
                            {{ getStatusText(currentSiteDetail.status) }}
                        </el-tag>
                    </el-descriptions-item>
                </el-descriptions>

                <!-- 监测数据趋势 -->
                <div v-if="currentSiteDetail.trendList && currentSiteDetail.trendList.length > 0" class="trend-section">
                    <h3 class="section-title">监测数据趋势</h3>
                    <div class="trend-charts">
                        <div v-for="trend in currentSiteDetail.trendList" :key="trend.name" class="trend-item">
                            <div class="trend-header">
                                <span class="trend-name">{{ trend.name }}</span>
                                <el-tag size="small" type="info">
                                    {{ getMonitoringUnit(trend.name) }}
                                </el-tag>
                            </div>
                            <div class="trend-chart-container">
                                <ECharts :option="chartOptions" />
                            </div>
                        </div>
                    </div>
                </div>

                <div v-else class="no-trend-data">
                    <el-empty description="暂无趋势数据" :image-size="80" />
                </div>
            </div>

            <template #footer>
                <el-button @click="handleCloseDetailDialog">关闭</el-button>
            </template> 
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import ECharts from '@/components/ECharts'

// API引入
import {
    getSiteTypeList,
    getMonitoringList,
    getSiteCardInfo,
    getSiteDetail
} from '@/api/dispatch/detection/guanwang_jiance'

// 筛选表单
const filterForm = reactive({
    siteTypeId: '',
    itemId: '',
    status: ''
})

// 站点类型选项
const siteTypeOptions = ref([])

// 监测量选项
const monitoringOptions = ref([])

// 站点数据
const siteData = ref([])
const loading = ref(false)

// 对话框控制
const detailDialogVisible = ref(false)
const trendDialogVisible = ref(false)
const currentSiteDetail = ref(null)
const currentTrendSite = ref(null)
const currentTrendData = ref(null)

// 趋势图参数
const trendPeriod = ref('24h')
const selectedMonitor = ref('')

const chartOptions = computed(() => {
    if(!currentSiteDetail.value.trendList) return;
    let legendData = currentSiteDetail.value.trendList.map(item => item.name)
    let xAxisData = currentSiteDetail.value.trendList[0].time;

    return {
        title: {
            text: '实时数据监控',
            left: 'center',
            textStyle: {
                color: '#333',
                fontSize: 16
            }
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                animation: false
            }
        },
        legend: {
            data: legendData,
            top: 30
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: xAxisData,
        },
        yAxis: {
            type: 'value',
        },
        series: currentSiteDetail.value.trendList.map(item => ({
            name:item.name,
            type: 'line',
            showSymbol: false,
            hoverAnimation: false,
            data: item.value,
        }))
    }
});

// 计算属性
const detailTitle = computed(() => {
    return currentSiteDetail.value ? `${currentSiteDetail.value.siteName} - 站点详情` : '站点详情'
})

const trendTitle = computed(() => {
    return currentTrendSite.value ? `${currentTrendSite.value.siteName} - 数据趋势` : '数据趋势'
})

// 初始化数据
onMounted(() => {
    initData()
})

// 初始化数据
const initData = async () => {
    try {
        await Promise.all([
            loadSiteTypeList(),
            loadMonitoringList()
        ])
        await loadSiteCardInfo()
    } catch (error) {
        console.error('初始化数据失败:', error)
        ElMessage.error('初始化数据失败')
    }
}

// 加载站点类型列表
const loadSiteTypeList = async () => {
    try {
        const res = await getSiteTypeList()
        siteTypeOptions.value = res.data || []
    } catch (error) {
        console.error('加载站点类型列表失败:', error)
        ElMessage.error('加载站点类型列表失败')
    }
}

// 加载监测量列表
const loadMonitoringList = async () => {
    try {
        const res = await getMonitoringList()
        monitoringOptions.value = res.data || []
        if (monitoringOptions.value.length > 0) {
            selectedMonitor.value = monitoringOptions.value[0].monitorId
        }
    } catch (error) {
        console.error('加载监测量列表失败:', error)
        ElMessage.error('加载监测量列表失败')
    }
}

// 加载站点卡片信息
const loadSiteCardInfo = async () => {
    try {
        loading.value = true
        const params = {
            siteTypeId: filterForm.siteTypeId,
            itemId: filterForm.itemId
        }

        const res = await getSiteCardInfo(params)
        siteData.value = res.data || []
    } catch (error) {
        console.error('加载站点信息失败:', error)
        ElMessage.error('加载站点信息失败')
    } finally {
        loading.value = false
    }
}

// 处理筛选变化
const handleFilterChange = () => {
    loadSiteCardInfo()
}

// 重置筛选
const resetFilter = () => {
    Object.assign(filterForm, {
        siteTypeId: '',
        itemId: '',
        status: ''
    })
    loadSiteCardInfo()
}

// 刷新数据
const refreshData = () => {
    loadSiteCardInfo()
    ElMessage.success('数据已刷新')
}

// 查看站点详情
const handleViewDetail = async (site) => {
    try {
        const res = await getSiteDetail(site.siteId)
        currentSiteDetail.value = res.data
        detailDialogVisible.value = true
    } catch (error) {
        console.error('获取站点详情失败:', error)
        ElMessage.error('获取站点详情失败')
    }
}

// 查看趋势图
const handleViewTrend = async (site) => {
    try {
        const res = await getSiteDetail(site.siteId)
        currentTrendSite.value = res.data
        trendDialogVisible.value = true
        // 模拟趋势数据
        generateTrendData()
    } catch (error) {
        console.error('获取趋势数据失败:', error)
        ElMessage.error('获取趋势数据失败')
    }
}

// 刷新单个站点
const handleRefreshSite = async (site) => {
    try {
        ElMessage.info(`正在刷新 ${site.siteName} 的数据...`)
        // 这里可以调用单独的刷新接口
        await loadSiteCardInfo()
        ElMessage.success(`${site.siteName} 数据已刷新`)
    } catch (error) {
        console.error('刷新站点数据失败:', error)
        ElMessage.error('刷新站点数据失败')
    }
}

// 关闭详情对话框
const handleCloseDetailDialog = () => {
    detailDialogVisible.value = false
    currentSiteDetail.value = null
}

// 关闭趋势对话框
const handleCloseTrendDialog = () => {
    trendDialogVisible.value = false
    currentTrendSite.value = null
    currentTrendData.value = null
}

// 处理时间范围变化
const handleTrendPeriodChange = (period) => {
    generateTrendData()
}

// 处理监测量变化
const handleMonitorChange = (monitorId) => {
    generateTrendData()
}

// 导出报表
const handleExportReport = (site) => {
    ElMessage.info(`导出 ${site.siteName} 的报表功能开发中`)
}

// 导出趋势图
const handleExportTrend = () => {
    ElMessage.info('导出趋势图功能开发中')
}

// 生成趋势数据（模拟）
const generateTrendData = () => {
    if (!currentTrendSite.value) return

    const monitor = monitoringOptions.value.find(m => m.monitorId === selectedMonitor.value)
    if (!monitor) return

    const labels = []
    const data = []

    // 生成24小时数据
    for (let i = 0; i < 24; i++) {
        const time = dayjs().subtract(23 - i, 'hour').format('HH:mm')
        labels.push(time)

        // 模拟数据波动
        const baseValue = 50 + Math.random() * 50
        data.push(Math.round(baseValue * 100) / 100)
    }

    currentTrendData.value = {
        labels,
        datasets: [
            {
                label: monitor.monitorName,
                data,
                borderColor: '#409EFF',
                backgroundColor: 'rgba(64, 158, 255, 0.1)',
                fill: true,
                tension: 0.4
            }
        ]
    }

    // 计算统计数据
    currentValue.value = data[data.length - 1]
    averageValue.value = Math.round(data.reduce((a, b) => a + b, 0) / data.length * 100) / 100
    maxValue.value = Math.round(Math.max(...data) * 100) / 100
    minValue.value = Math.round(Math.min(...data) * 100) / 100
}

// 工具函数
const getSiteTypeName = (typeId) => {
    const type = siteTypeOptions.value.find(item => item.dictValue === typeId)
    return type ? type.dictLabel : typeId || '未知'
}

const getSiteTypeTag = (typeId) => {
    const types = {
        'pump_station': 'primary',
        'water_plant': 'success',
        'valve_chamber': 'warning',
        'monitor_point': 'info',
        'reservoir': 'danger'
    }
    return types[typeId] || 'info'
}

const getMonitoringUnit = (monitorName) => {
    const units = {
        '压力': 'MPa',
        '流量': 'm³/h',
        '温度': '°C',
        '水位': 'm',
        'pH值': '',
        '浊度': 'NTU',
        '余氯': 'mg/L'
    }
    return units[monitorName] || ''
}

const getStatusTag = (status) => {
    if (status === 0) return 'success' // 正常
    if (status === 1) return 'danger'  // 报警
    if (status === 2) return 'warning' // 警告
    return 'info' // 未知
}

const getStatusText = (status) => {
    if (status === 0) return '正常'
    if (status === 1) return '报警'
    if (status === 2) return '警告'
    return status || '未知'
}

const getSiteCardClass = (site) => {
    const hasAlarm = site.nodeList?.some(node => node.status === 1)
    const hasWarning = site.nodeList?.some(node => node.status === 2)

    if (hasAlarm) return 'card-alarm'
    if (hasWarning) return 'card-warning'
    return 'card-normal'
}

const getDataItemClass = (node) => {
    if (node.status === 1) return 'data-item-alarm'
    if (node.status === 2) return 'data-item-warning'
    return 'data-item-normal'
}

const hasTrendData = (site) => {
    return site.nodeList && site.nodeList.length > 0
}

const formatTime = (timeString) => {
    if (!timeString) return '-'
    try {
        return dayjs(timeString).format('HH:mm:ss')
    } catch {
        return timeString
    }
}

const formatDateTime = (dateTimeString) => {
    if (!dateTimeString) return '-'
    try {
        return dayjs(dateTimeString).format('YYYY-MM-DD HH:mm:ss')
    } catch {
        return dateTimeString
    }
}

// 模拟统计数据
const currentValue = ref(0)
const averageValue = ref(0)
const maxValue = ref(0)
const minValue = ref(0)
</script>

<style scoped lang="scss">
.app-container {
    padding: 20px;
}

.page-header {
    margin-bottom: 24px;
    text-align: center;
}

.page-title {
    font-size: 24px;
    font-weight: 600;
    color: #303133;
    margin: 0 0 8px 0;
}

.page-subtitle {
    font-size: 14px;
    color: #909399;
    margin: 0;
}

.filter-card {
    margin-bottom: 20px;
}

.filter-form {
    .el-row {
        margin-bottom: 0;
    }
}

.filter-actions {
    padding-top: 29px;
    text-align: center;
}

.cards-container {
    min-height: 400px;
}

.loading-container {
    padding: 40px 0;
}

.empty-container {
    padding: 60px 0;
}

.cards-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
    gap: 20px;
    margin-bottom: 20px;
}

.site-card {
    transition: all 0.3s ease;
    border-radius: 8px;
    overflow: hidden;

    &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    }

    &.card-normal {
        border-left: 4px solid #67c23a;
    }

    &.card-warning {
        border-left: 4px solid #e6a23c;
    }

    &.card-alarm {
        border-left: 4px solid #f56c6c;
    }
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 16px;
    padding-bottom: 12px;
    border-bottom: 1px solid #e4e7ed;
}

.site-info {
    flex: 1;
}

.site-name {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    margin: 0 0 8px 0;
    line-height: 1.4;
}

.site-type {
    margin-top: 4px;
}

.card-actions {
    flex-shrink: 0;
    margin-left: 12px;
}

.monitoring-data {
    margin-bottom: 16px;
}

.data-item {
    display: grid;
    grid-template-columns: 1fr auto;
    grid-template-rows: auto auto;
    gap: 8px 16px;
    padding: 12px;
    margin-bottom: 8px;
    border-radius: 6px;
    border: 1px solid #e4e7ed;
    transition: all 0.2s ease;

    &.data-item-normal {
        background: #f5f7fa;
    }

    &.data-item-warning {
        background: #fdf6ec;
        border-color: #e6a23c;
    }

    &.data-item-alarm {
        background: #fef0f0;
        border-color: #f56c6c;
    }

    &:last-child {
        margin-bottom: 0;
    }
}

.data-label {
    grid-column: 1;
    grid-row: 1;
    display: flex;
    align-items: center;
    gap: 4px;
}

.label-text {
    font-size: 14px;
    font-weight: 500;
    color: #606266;
}

.unit-icon {
    color: #909399;
    font-size: 12px;
    cursor: help;
}

.data-value {
    grid-column: 2;
    grid-row: 1;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    gap: 4px;
}

.value-number {
    font-size: 18px;
    font-weight: 600;
    color: #303133;
}

.value-unit {
    font-size: 12px;
    color: #909399;
}

.data-status {
    grid-column: 1;
    grid-row: 2;
}

.data-time {
    grid-column: 2;
    grid-row: 2;
    font-size: 12px;
    color: #909399;
    text-align: right;
}

.card-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-top: 12px;
    border-top: 1px solid #e4e7ed;
}

.update-time {
    font-size: 12px;
    color: #909399;
}

.footer-right {
    flex-shrink: 0;
}

/* 详情对话框样式 */
.site-detail {
    max-height: 70vh;
    overflow-y: auto;
}

.trend-section {
    margin-top: 24px;
}

.section-title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    margin: 0 0 16px 0;
    padding-bottom: 8px;
    border-bottom: 1px solid #e4e7ed;
}

.trend-charts {
    display: grid;
    gap: 24px;
}

.trend-item {
    border: 1px solid #e4e7ed;
    border-radius: 6px;
    padding: 16px;
    background: #fafafa;
}

.trend-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
}

.trend-name {
    font-size: 14px;
    font-weight: 500;
    color: #303133;
}

.trend-chart-container {
}

.no-trend-data {
    padding: 40px 0;
    text-align: center;
}

/* 趋势图对话框样式 */
.trend-detail {
    max-height: 70vh;
    overflow-y: auto;
}

.trend-filter {
    display: flex;
    gap: 16px;
    margin-bottom: 24px;
    padding: 16px;
    background: #f5f7fa;
    border-radius: 6px;
}

.trend-chart-main {
    height: 400px;
    margin-bottom: 24px;
    border: 1px solid #e4e7ed;
    border-radius: 6px;
    padding: 16px;
    background: white;
}

.trend-stats {
    margin-top: 24px;
}

.stat-item {
    text-align: center;
    padding: 16px;
    background: #f5f7fa;
    border-radius: 6px;
    border: 1px solid #e4e7ed;
}

.stat-label {
    font-size: 12px;
    color: #909399;
    margin-bottom: 8px;
}

.stat-value {
    font-size: 18px;
    font-weight: 600;
    color: #303133;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .cards-grid {
        grid-template-columns: 1fr;
    }

    .filter-form .el-col {
        margin-bottom: 15px;
    }

    .card-header {
        flex-direction: column;
        align-items: stretch;
        gap: 12px;
    }

    .card-actions {
        margin-left: 0;
        justify-content: flex-end;
    }

    .data-item {
        grid-template-columns: 1fr;
        grid-template-rows: auto auto auto auto;
        gap: 8px;
    }

    .data-value {
        grid-column: 1;
        grid-row: 2;
        justify-content: flex-start;
    }

    .data-status {
        grid-column: 1;
        grid-row: 3;
    }

    .data-time {
        grid-column: 1;
        grid-row: 4;
        text-align: left;
    }

    .card-footer {
        flex-direction: column;
        gap: 12px;
        align-items: stretch;
    }

    .footer-right {
        align-self: center;
    }

    .trend-filter {
        flex-direction: column;
    }
}

@media (max-width: 480px) {
    .app-container {
        padding: 10px;
    }

    .page-title {
        font-size: 20px;
    }

    .site-name {
        font-size: 14px;
    }

    .value-number {
        font-size: 16px;
    }
}
</style>